package com.yyq.adms.sysmanage.bpo.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.dom.DOMElement;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.yyq.adms.sysmanage.bpo.SysModulesBpo;
import com.yyq.adms.sysmanage.dao.SysModulesDao;
import com.yyq.adms.sysmanage.pojo.SysModules;
import com.yyq.adms.usermanage.pojo.SysRPM;
import com.yyq.adms.usermanage.pojo.SysUsersRoles;
import com.yyq.sos.pojo.MenuNodeEntity;
import com.yyq.sos.pojo.TreeNodeEntity;
import com.yyq.sos.service.BaseBpoImpl;

/**
 * 系统模块的业务处理实现类
 * @author Administrator
 *
 */
@Service("sysModulesBpo")
@Transactional
public class SysModulesBpoImpl extends BaseBpoImpl implements SysModulesBpo {
	private SysModulesDao dao;
	@Resource(name="sysModulesDao") 
	public void setDao(SysModulesDao dao) {
		this.dao = dao;
		super.setBaseDao(dao);
	}

	/**
	 * 创建模块列表树DOM，返回DOM字符串
	 * @return
	 */
	/*public String getTree()
	{
		Document doc=DocumentHelper.createDocument();
		Element parent = this.createParentNode(doc);
		List list = dao.list("from "+SysModules.class.getName()+"  where parentId=0");
		int count = list.size();
		for(int i=0; i<count; ++i)
		{
			SysModules obj = (SysModules)list.get(i);
			parent.add(this.createChildNode(obj));
		}
		return doc.asXML();
	}*/
	
	public String getTree()
	{
		List<TreeNodeEntity> treeNodes = new ArrayList<TreeNodeEntity>();
		TreeNodeEntity parent = new TreeNodeEntity();
		parent.setId(0);
		parent.setPId(-1);
		parent.setName("模块列表");
		parent.setClick(false);
		parent.setOpen(true);
		treeNodes.add(parent);
		List list = dao.list("from "+SysModules.class.getName()+"  where isMenu=1");
		int count = list.size();
		for(int i=0; i<count; ++i)
		{
			SysModules obj = (SysModules)list.get(i);
			TreeNodeEntity child = new TreeNodeEntity();
			child.setId(obj.getId().intValue());
			child.setPId(obj.getParentId().intValue());
			child.setName(obj.getModuleCname());
			child.setTitle(obj.getModuleName());
			treeNodes.add(child);
		}
		Gson gson = new Gson();
		return gson.toJson(treeNodes);
	}
	
	/**
	 * 创建模块列表树的子节点
	 * @param obj
	 * @return
	 */
	private Element createChildNode(SysModules obj)
	{
		Element node = new DOMElement("item");
		node.addAttribute("text", obj.getModuleCname());
		node.addAttribute("id", String.valueOf(obj.getId()));
		node.addAttribute("tooltip", obj.getModuleName());
		node.addAttribute("open", "1");
		node.addAttribute("im0", "books_close.gif");
		node.addAttribute("im1", "books_close.gif");
		node.addAttribute("im2", "tombs.gif");
		return node;
	}
	
	/**
	 * 创建模块列表树的父节点
	 * @param obj
	 * @return
	 */
	private Element createParentNode(Document doc)
	{	
		doc.setXMLEncoding("GBK");
		Element root=doc.addElement("tree");
		root.addAttribute("id", "-1");
		Element tree = new DOMElement("item");
		tree.addAttribute("text", "模块列表");
		tree.addAttribute("id", "0");
		tree.addAttribute("tooltip", "模块列表");
		tree.addAttribute("open", "1");
		tree.addAttribute("im0", "books_close.gif");
		tree.addAttribute("im1", "tombs.gif");
		tree.addAttribute("im2", "tombs.gif");
		tree.addAttribute("call", "1");
		tree.addAttribute("select", "1");
		root.add(tree);
		return tree;
	}
	
	/**
	 * 取得左侧的导航菜单
	 */
	public String getMenu(String userId) {
		String sql = "select distinct obj from "+SysModules.class.getName()+" obj,"
					+SysUsersRoles.class.getName()+" objUR,"
					+SysRPM.class.getName()+" objRPM "
					+" where obj.parentId<>0 and objUR.userId="+userId +" and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.moduleId and obj.isMenu=1 order by obj.moduleLevel asc";
		if(userId.equals("1"))
			sql = "from "+SysModules.class.getName()+" where isMenu=1 order by moduleLevel asc" ;
		List list = dao.list(sql);
		if(list.size()==0)
			return "";
		if(!userId.equals("1")){
			sql = "from "+SysModules.class.getName()+" where ";
			String rel = "";
			for(int i=0; i<list.size();++i){
				int pid = ((SysModules)list.get(i)).getParentId().intValue();
				if(pid!=0){
					sql += rel + "moduleId="+pid;
					rel =  " or ";
				}
			}
			//******************************************  非all用户左侧菜单目录排序
			sql+=" order by moduleId desc";
System.out.println("sql---------->"+sql);
			List parents = dao.list(sql);
			for(int i=0; i<parents.size(); ++i){
				SysModules p = (SysModules)parents.get(i);
				boolean bool = false;
				for(int j=0; j<list.size(); ++j){
					int c = ((SysModules)list.get(j)).getId().intValue();
					if(p.getId().intValue()==c){
						bool = true;
						break;
					}
				}
				if(!bool){
					list.add(0, p);
				}
			}
		}
		return this.createMenuDom(list);
	}
	
	public List<SysModules> getModulesMenuListByUserId(String userId){
		String sql = "select distinct obj from "
				+ SysModules.class.getName()
				+ " obj,"
				+ SysUsersRoles.class.getName()
				+ " objUR,"
				+ SysRPM.class.getName()
				+ " objRPM "
				+ " where obj.parentId<>0 and objUR.userId="
				+ userId
				+ " and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.id and obj.isMenu=1 order by obj.moduleLevel asc";
		if (userId.equals("1"))
			sql = "from " + SysModules.class.getName()
					+ " where isMenu=1 order by moduleLevel asc";
		List<SysModules> list = dao.list(sql);
		if (list.size() == 0)
			return null;
		if (!userId.equals("1")) {
			sql = "from " + SysModules.class.getName() + " where ";
			String rel = "";
			for (int i = 0; i < list.size(); ++i) {
				int pid = list.get(i).getParentId().intValue();
				if (pid != 0) {
					sql += rel + "id=" + pid;
					rel = " or ";
				}
			}
			// ****************************************** 非all用户左侧菜单目录排序
			sql += " order by id desc";
			System.out.println("sql---------->" + sql);
			List<SysModules> parents = dao.list(sql);
			for (int i = 0; i < parents.size(); ++i) {
				SysModules p =  parents.get(i);
				boolean bool = false;
				for (int j = 0; j < list.size(); ++j) {
					int c = ((SysModules) list.get(j)).getId().intValue();
					if (p.getId().intValue() == c) {
						bool = true;
						break;
					}
				}
				if (!bool) {
					list.add(0, p);
				}
			}
		}
		return list;
	}
	
	
	/**
	 * 创建左侧导航菜单的Dom，并转换为字符串返回
	 * @param list
	 * @return
	 */
	private String createMenuDom(List list)
	{
		Element root = this.createRootMenu();
		int count = list.size();
		Map map = new HashMap();
		for(int i=0; i<count; ++i)
		{
			Element childTop = null;
			SysModules vo = (SysModules)list.get(i);
			if(vo.getParentId().intValue()==0){
				root.add(this.createParentMenu(vo.getId().longValue(), vo.getModuleCname()));
				childTop = this.createChildTopMenu(root, vo.getId().longValue());
				map.put(vo.getId(), childTop);
			}
		}
		for(int i=0; i<count; ++i)
		{
			SysModules vo = (SysModules)list.get(i);
			if(vo.getParentId().intValue()!=0){
				Element elem = (Element)map.get(vo.getParentId());
				elem.add(this.createChildMenu(vo));
			}
		}
		String menu = root.getDocument().asXML();
		menu = menu.substring(menu.indexOf("table")+6,menu.lastIndexOf("table")-2);
		return menu;
	}
	
	/**
	 * 创建左侧导航菜单的子菜单
	 * @param vo
	 * @return
	 */
	private Element createChildMenu(SysModules vo)
	{
		String url ="";
		if(vo.getModuleUrl().indexOf("?")>0)
			url = vo.getModuleUrl()+"&formMap.moduleId="+vo.getId()+"&formMap.className="+vo.getModuleName();
		else
			url = vo.getModuleUrl()+"?formMap.moduleId="+vo.getId()+"&formMap.className="+vo.getModuleName();
		Element child = new DOMElement("tr");
		Element tdElem = child.addElement("td");
		tdElem.addElement("img").addAttribute("height", "14")
								.addAttribute("src", "../img/tu_dc.gif")
								.addAttribute("width", "16")
								.addAttribute("border", "0");
		tdElem.addElement("a").addAttribute("target", "mainFrame")
							  .addAttribute("href", "../"+url)
			  .addElement("font").addAttribute("size", "2").addText(vo.getModuleCname());
		return child;
	}
	
	/**
	 * 创建左侧导航菜单的子菜单的上级容器
	 * @param doc
	 * @param id
	 * @return
	 */
	private Element createChildTopMenu(Element root,long id){
		Element childTable = new DOMElement("table");
		Element childTop = new DOMElement("tr");
		Element childTD  = childTop.addElement("td");
		childTD.addAttribute("height", "60")
								 .addAttribute("id", "submenu"+id)
								 .addAttribute("style","DISPLAY: none")
				.addElement("div").addAttribute("class", "sec_menu")
								  .addAttribute("style","WIDTH: 158px")
				.add(childTable);
		childTD.addElement("br");
		childTable.addAttribute("cellspacing", "3")
				  .addAttribute("cellpadding", "0")
				  .addAttribute("width", "158").addAttribute("align", "center");
		root.add(childTop);
		return childTable;
	}
	
	/**
	 * 创建左侧导航菜单的父菜单
	 * @param id
	 * @param name
	 * @return
	 */
	private Element createParentMenu(long id, String name)
	{
		Element p = new DOMElement("tr");
		p.addElement("td").addAttribute("id", "imgmenu"+id)
			.addAttribute("class", "menu_title")
			.addAttribute("onMouseOver","this.className='menu_title2';")
			.addAttribute("onClick", "showsubmenu("+id+")")
			.addAttribute("onMouseOut", "this.className='menu_title';")
			.addAttribute("style", "cursor: hand")
			.addAttribute("background", "../img/menudown.gif")
			.addAttribute("height", "25")
		    .addElement("span").addElement("font").addAttribute("size", "2").addText("    "+name);
		return p;
	}
	
	/**
	 * 创建左侧导航菜单的DOM对象
	 * @return
	 */
	private Element createRootMenu()
	{
		Document doc=DocumentHelper.createDocument();
		doc.setXMLEncoding("GBK");
		Element root = new DOMElement("table");
		doc.setRootElement(root);
		return root;
	}
	
	
	public static void main(String[] sss)
	{
		//SysModulesBpoImpl bpo = new SysModulesBpoImpl(new SysModulesDaoImpl(),SysModules.class);
		//bpo.getMenu("1");
	}

	public String getMenuByGroup(String userId) {
		String treeZL = getResultMessage(userId);
		if(treeZL==null || treeZL.trim().equals("")){
			treeZL = "\"\"";
		}
		String menu = "{TEST:[{AA:1}],ZHANGLI:"+treeZL+"}";
		return menu;
	}
	
	public String getResultMessage(String userId){
		MenuNodeEntity root = new MenuNodeEntity();
		int rootId = 131;
		root.setId(rootId);
		recursiveMenu(userId,rootId+"",root);
		List<MenuNodeEntity> children = root.getChildren();
		String menuStr = "";
		if(children != null){
			Gson gson = new Gson();
			menuStr = gson.toJson(children);
		}
		return menuStr;
	}
	
	private void recursiveMenu(String userId,String parentId,MenuNodeEntity root){
		String sql = "select distinct obj from "
			+ SysModules.class.getName()
			+ " obj,"
			+ SysUsersRoles.class.getName()
			+ " objUR,"
			+ SysRPM.class.getName()
			+ " objRPM "
			+ " where obj.parentId="+parentId+" and objUR.userId="
			+ userId
			+ " and objUR.roleId=objRPM.roleId and objRPM.moduleId=obj.id and obj.isMenu=1 order by obj.moduleLevel,obj.id asc";
		if (userId.equals("1"))
			sql = "from " + SysModules.class.getName()+ " where parentId="+parentId+" and isMenu=1 order by moduleLevel,id asc";
		
		List list = dao.list(sql);
		if (list.size() == 0)
			return;
		List<MenuNodeEntity> children = new ArrayList<MenuNodeEntity>();
		for(int i=0;i<list.size();i++){
			SysModules m = (SysModules)list.get(i);
			String url ="";
			MenuNodeEntity node = new MenuNodeEntity();
			node.setId(m.getId().intValue());
			node.setPId(m.getParentId().intValue());
			node.setName(m.getModuleCname());
			node.setOpen(false);
			if(!"URL".equalsIgnoreCase(m.getModuleUrl())){
				if(m.getModuleUrl().indexOf("?")>0)
					url = m.getModuleUrl()+"&formMap.moduleId="+m.getId()+"&formMap.className="+m.getModuleName();
				else
					url = m.getModuleUrl()+"?formMap.moduleId="+m.getId()+"&formMap.className="+m.getModuleName();
				node.setUrl(url);
				node.setTarget("mainFrame");
			}
			node.setTitle(m.getModuleName());
			//node.setIconOpen("../css/img/minus.gif");
			//node.setIconClose("../css/img/plus.gif");
			//node.setIcon("../css/img/folder.gif");
			children.add(node);
			recursiveMenu(userId,m.getId()+"",node);
		}
		root.setChildren(children);
		
	}
	
	
	
}
